﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace gbL.NetBoard.Examples.DoubleMVC.View.UI
{
    class ColumnDef<T>
    {
        public ColumnDef(string title, Func<T, string> valueExtract, bool alignRight)
        {
            Title = title;
            ValueExtract = valueExtract;
            AlignRight = alignRight;
        }
        public bool AlignRight { get; set; }
        public int Width { get; set; }
        public string Title { get; set; }
        public Func<T, string> ValueExtract { get; set; }
        public void CalculateWidth(IEnumerable<T> data)
        {
            Width = data.Max(x => ValueExtract(x).Length);
            if (Width < Title.Length) Width = Title.Length;
        }
        public void OutputColumnCell(T dataItem, IOutputTarget output, bool rightSpace)
        {
            string content = ValueExtract(dataItem);
            content = OutputContent(output, rightSpace, content);
        }

        private string OutputContent(IOutputTarget output, bool rightSpace, string content)
        {
            if (content.Length > Width) content = content.Substring(0, Width);
            if (content.Length < Width)
            {
                string buffer = new string(' ', Width - content.Length);
                if (AlignRight)
                    content = buffer + content;
                else
                    content += buffer;
            }
            output.Write(content);
            if (rightSpace) output.Write(" ");
            return content;
        }

        public void OutputTitleCell(IOutputTarget output)
        {
            OutputContent(output, true, Title);
        }
    }
}
